package com.amu.aidemo.ui

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TestScreen(
    onBack: () -> Unit,
    onStartAsr: (onRealtimeResult: (String) -> Unit) -> Unit,
    onStopAsr: (onResult: (String) -> Unit) -> Unit,
    onTestLlm: (String, onResult: (String) -> Unit) -> Unit,
    onTestTts: (String) -> Unit
) {
    var asrResult by remember { mutableStateOf("") }
    var asrTesting by remember { mutableStateOf(false) }
    
    var llmInput by remember { mutableStateOf("今天天气怎么样？") }
    var llmResult by remember { mutableStateOf("") }
    var llmTesting by remember { mutableStateOf(false) }
    
    var ttsInput by remember { mutableStateOf("你好，这是语音合成测试。") }
    var ttsTesting by remember { mutableStateOf(false) }
    
    val coroutineScope = rememberCoroutineScope()
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("模块测试") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, "返回")
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            // ASR 测试
            TestSection(
                title = "语音识别 (ASR) 测试",
                description = "点击开始录音，再次点击停止并识别"
            ) {
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Button(
                        onClick = {
                            if (!asrTesting) {
                                // 开始录音
                                asrTesting = true
                                asrResult = ""
                                onStartAsr { realtimeResult ->
                                    // 实时更新识别结果
                                    asrResult = realtimeResult
                                }
                            } else {
                                // 停止录音并获取最终结果
                                onStopAsr { result ->
                                    asrResult = result
                                    asrTesting = false
                                }
                            }
                        },
                        colors = if (asrTesting) {
                            ButtonDefaults.buttonColors(
                                containerColor = MaterialTheme.colorScheme.error
                            )
                        } else {
                            ButtonDefaults.buttonColors()
                        },
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Text(if (asrTesting) "停止录音" else "开始录音")
                    }
                    
                    if (asrResult.isNotEmpty()) {
                        ResultCard(
                            title = if (asrTesting) "实时识别中..." else "识别结果",
                            content = asrResult.ifEmpty { "等待语音输入..." }
                        )
                    }
                }
            }
            
            Divider()
            
            // LLM 测试
            TestSection(
                title = "大语言模型 (LLM) 测试",
                description = "输入问题，获取 AI 回复"
            ) {
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    OutlinedTextField(
                        value = llmInput,
                        onValueChange = { llmInput = it },
                        label = { Text("输入问题") },
                        modifier = Modifier.fillMaxWidth(),
                        enabled = !llmTesting,
                        minLines = 2
                    )
                    
                    Button(
                        onClick = {
                            llmTesting = true
                            llmResult = "正在思考..."
                            onTestLlm(llmInput) { result ->
                                llmResult = result
                                llmTesting = false
                            }
                        },
                        enabled = !llmTesting && llmInput.isNotBlank(),
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Text(if (llmTesting) "思考中..." else "开始 LLM 测试")
                    }
                    
                    if (llmResult.isNotEmpty()) {
                        ResultCard(
                            title = "AI 回复",
                            content = llmResult
                        )
                    }
                }
            }
            
            Divider()
            
            // TTS 测试
            TestSection(
                title = "语音合成 (TTS) 测试",
                description = "输入文本，播放合成语音"
            ) {
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    OutlinedTextField(
                        value = ttsInput,
                        onValueChange = { ttsInput = it },
                        label = { Text("输入文本") },
                        modifier = Modifier.fillMaxWidth(),
                        enabled = !ttsTesting,
                        minLines = 2
                    )
                    
                    Button(
                        onClick = {
                            ttsTesting = true
                            onTestTts(ttsInput)
                            // TTS 播放是异步的，3秒后恢复按钮
                            coroutineScope.launch {
                                delay(3000)
                                ttsTesting = false
                            }
                        },
                        enabled = !ttsTesting && ttsInput.isNotBlank(),
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Text(if (ttsTesting) "播放中..." else "开始 TTS 测试")
                    }
                }
            }
        }
    }
}

@Composable
private fun TestSection(
    title: String,
    description: String,
    content: @Composable () -> Unit
) {
    Column(
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold
        )
        Text(
            text = description,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        Spacer(modifier = Modifier.height(4.dp))
        content()
    }
}

@Composable
private fun ResultCard(
    title: String,
    content: String
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.secondaryContainer
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Text(
                text = title,
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onSecondaryContainer,
                fontWeight = FontWeight.Bold
            )
            Text(
                text = content,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSecondaryContainer
            )
        }
    }
}
